﻿<%@ Page Language="C#" %>
<%@ Import Namespace="Findy.XsltDb" %>
<%@ Import Namespace="System.IO" %>


<script runat="server">
/*
 XsltDb is powerful XSLT module for DotnetNuke.
 It offers safe database access, SEO-friendly AJAX support,
 visitor interactions, environment integration (dnn properties,
 request, cookie, session and form values), regular expressions, etc.

 Author:
 
    Anton Burtsev
    burtsev@yandex.ru

 Project home page: 
 
    http://xsltdb.codeplex.com
*/

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            var encoded = Request["enc"] == "1";
            var justUpload = (Request["ju"] ?? string.Empty) == "1";
            var portal = (Request["p"] ?? string.Empty) == "1";
            var persistent = (Request["keep"] ?? string.Empty) != "0";
            var wText = Request["wt"] ?? string.Empty;
            var wPath = Request["wp"] ?? string.Empty;
            var path = Request["file"].ToLower();
            var format = (Request["f"] ?? "auto").ToLower();
            var q = Convert.ToInt32(Request["q"] ?? "80");
            var w = Convert.ToInt32(Request["w"] ?? "0");
            var h = Convert.ToInt32(Request["h"] ?? "0");
            var clientCache = Convert.ToInt32(Request["cc"] ?? (60 * 6).ToString());

            var x1 = Convert.ToInt32(Request["x1"] ?? "0");
            var y1 = Convert.ToInt32(Request["y1"] ?? "0");
            var x2 = Convert.ToInt32(Request["x2"] ?? "0");
            var y2 = Convert.ToInt32(Request["y2"] ?? "0");

            var breaker = Request["s"];


            if (format == "auto")
            {
                var ext = Path.GetExtension(path).ToLower();
                while (ext.StartsWith(".")) ext = ext.Substring(1);
                if (ext == "jpg" || ext == "jpeg" || ext == "png" || ext == "gif")
                    format = ext;
                else
                    format = "jpeg";
            }
            if (format == "jpg") format = "jpeg";
            if (format == "tif") format = "tiff";

            Response.ContentType = "image/" + format;

            if (encoded)
                path = path.Replace("_", "\\");

            string headers = Request["headers"];

            if (!string.IsNullOrEmpty(headers))
            {
                foreach (var s in headers.Split('&'))
                {
                    string[] parts = s.Split('=');
                    Response.Headers[parts[0]] = parts[1];
                }
            }

            string fullPath;

            if (portal)
            {
                fullPath = FileMan.PathCombine(
                    PortalController.GetCurrentPortalSettings().HomeDirectoryMapPath,
                    path);
            }
            else
            {
                fullPath = FileMan.PathCombine(Request.PhysicalApplicationPath,
                    Helper.getFilesRoot(PortalController.GetCurrentPortalSettings().PortalId),
                    path);
            }

            if (justUpload)
            {
                var allBytes = File.ReadAllBytes(fullPath);
                var etag = Request.Headers["If-None-Match"] ?? string.Empty;
                var hash = allBytes.MD5();
                if (etag == hash)
                {
                    Response.Status = "304 Not Modified";
                    Response.StatusCode = 304;
                }
                else
                {
                    Response.OutputStream.Write(allBytes, 0, allBytes.Length);
                    Response.AddHeader("ETag", hash);
                }
            }
            else
            {

                var args = new ImageTools.ThumbnailArgs
                               {
                                   OriginalPath = fullPath,
                                   Width = w,
                                   Height = h,
                                   x1 = x1,
                                   y1 = y1,
                                   x2 = x2,
                                   y2 = y2,
                                   IsPersistent = persistent,
                                   Format = format,
                                   WatermarkPath =
                                       string.IsNullOrEmpty(wPath)
                                           ? null
                                           : FileMan.PathCombine(
                                               PortalController.GetCurrentPortalSettings().HomeDirectoryMapPath, wPath),
                                   WatermarkText = wText,
                                   Quality = q,
                                   Breaker = breaker
                               };
                var t = ImageTools.CreateThumbnail(args);
                if (t != null)
                {
                    string etag = Request.Headers["If-None-Match"] ?? string.Empty;
                    string hash = t.ThumbnailBytes.MD5();
                    if (etag == hash)
                    {
                        Response.Status = "304 Not Modified";
                        Response.StatusCode = 304;
                    }
                    else
                    {
                        Response.OutputStream.Write(t.ThumbnailBytes, 0, t.ThumbnailBytes.Length);
                        Response.AddHeader("ETag", hash);
                    }
                }

                Response.AddHeader("Expires", DateTime.UtcNow.AddMinutes(clientCache).ToString("r"));
            }
            XsltDbUtils.UpdateCulture();
        }
        catch (Exception ex)
        {
            XsltDbUtils.WriteLog(ex);
        }
    }

</script>

